#!/bin/bash
#
# https://github.com/Aniverse/inexistence
# Author: Aniverse

script_update=2020.08.09
script_version=r11014

################################################################################################ Debug

usage_for_debug() {
    export local_packages=/etc/inexistence/00.Installation
    export s=$local_packages/package/filebrowser
    rm -f $s ; nano $s
    if [[ -f /etc/inexistence/00.Installation/package/filebrowser ]]; then
        bash /etc/inexistence/00.Installation/package/filebrowser -u $iUser -p $iPass
    else
        bash <(wget -qO- https://github.com/Aniverse/inexistence/raw/master/00.Installation/package/filebrowser)
    fi
}

################################################################################################

unset LogRootPath LogTimes DebLocation SCLocation LOCKLocation OutputLOG

function show_usage() { echo "
$AppName $pm_action $script_version ($script_update)
Usage:
      -u        Username for FileBrowser
      -p        Password for FileBrowser
      -l        Specifiy LogBase (Not log file)
      -d        Enable debug mode
      -w        WebUI port for FileBrowser
      -f        Force recover existing configuration
      --log     Show logfile's content"
exit 1 ; }

OPTS=$(getopt -o v:l:w:u:df -al username:,password:,version:,debug,logbase:,wport:,log,force -- "$@")
[ ! $? = 0 ] && show_usage
eval set -- "$OPTS"

while [ -n "$1" ] ; do case "$1" in
    -u | --username     ) iUser="$2"    ; shift 2 ;;
    -p | --password     ) iPass="$2"    ; shift 2 ;;
    -v | --version      ) version="$2"  ; shift 2 ;;
    -l | --logbase      ) LogTimes="$2" ; shift 2 ;;
    -w | --wport        ) wPort="$2"    ; shift 2 ;;
    -d | --debug        ) debug=1       ; shift   ;;
    -f | --force        ) force=1       ; shift   ;;
         --log          ) show_log=1    ; shift   ;;
    -- ) shift ; break ;;
esac ; done

AppName=FileBrowser
AppNameLower=filebrowser
AppExec=""
AppTest="docker ps | grep filebrowser | grep $iUser"
Need_SourceCode=no
pm_action=install

################################################################################################ Set Variables

if [[ -f /etc/inexistence/00.Installation/function ]]; then
    source /etc/inexistence/00.Installation/function
else
    source <(wget -qO- https://github.com/Aniverse/inexistence/raw/master/00.Installation/function)
fi

set_variables_log_location
check_var_OutputLOG
debug_log_location
cat_outputlog
check_var_iUser_iPass_iHome

[[ -z $wPort ]] && wPort=7575
wPort2=7576
[[ -z $lang ]] && lang=zh-cn
PortCheck $wPort
[[ $port_used == 1 ]] && echo_error_exit "Please change your port"

################################################################################################

function get_filebrowser_origin () {
    mkdir -p /tmp/fb && cd /tmp/fb
    # wget -nv https://github.com/filebrowser/filebrowser/releases/download/v2.0.16/linux-amd64-filebrowser.tar.gz  >> "$OutputLOG" 2>&1
    latest=$(wget -qO- https://api.github.com/repos/filebrowser/filebrowser/releases/latest | grep browser_download_url | grep linux-amd64 | cut -d '"' -f 4)
    wget $latest -O linux-amd64-filebrowser.tar.gz     >> "$OutputLOG" 2>&1
    tar zxf linux-amd64-filebrowser.tar.gz             >> "$OutputLOG" 2>&1
    mv /tmp/fb/filebrowser /usr/local/bin/filebrowser  >> "$OutputLOG" 2>&1
    cd && rm -rf /tmp/fb/filebrowser
}

function get_filebrowser_ee () {
    docker pull 80x86/filebrowser:amd64 >> "$OutputLOG" 2>&1
}

function create_filebrowser_conf () {
    local user=$1
    [[ $user == root ]] && local uhome=/root || local uhome=/home/$user
    rm -rf   $uhome/.config/filebrowser-ee
    mkdir -p $uhome/.config/filebrowser-ee/log
    /usr/local/bin/filebrowser -d $uhome/.config/filebrowser-ee/database.db config init                                     >> "$OutputLOG" 2>&1
    /usr/local/bin/filebrowser -d $uhome/.config/filebrowser-ee/database.db config set --locale  $lang                      >> "$OutputLOG" 2>&1
    /usr/local/bin/filebrowser -d $uhome/.config/filebrowser-ee/database.db users add $iUser $iPass --perm.admin            >> "$OutputLOG" 2>&1
    chown ${user}.${user} -R ${uhome}/.config/filebrowser-ee/
}

function create_filebrowser_systemd () {
    local user=$1
    _UID=$(id -u ${user})
    _GID=$(id -g ${user})
    if [[ $user == root ]]; then
        local unit=filebrowser-root.service
        local suffix=""
        local mountpoint="/"
        local PORT=$wPort2
        local uhome=/root
        local url=fb
    else
        local unit=filebrowser@${user}.service
        local suffix="-${user}"
        local mountpoint="/home/${user}/"
        local PORT=$wPort
        local uhome=/home/$user
        local url=filebrowser
    fi
    cat << EOF > /etc/systemd/system/$unit
[Unit]
Description=File Browser Enhanced Edition
After=docker.service
Requires=docker.service

[Service]
TimeoutStartSec=0
ExecStartPre=-/usr/bin/docker stop filebrowser${suffix}
ExecStartPre=-/usr/bin/docker rm filebrowser${suffix}
#ExecStartPre=/usr/bin/docker pull 80x86/filebrowser:amd64
ExecStart=/usr/bin/docker run \
-e PUID=$_UID \
-e PGID=$_GID \
-e WEB_PORT=${PORT} \
-e UMASK_SET=133 \
-e FB_BASEURL="/$url/" \
-p ${PORT}:${PORT} \
-v ${uhome}/.config/filebrowser-ee:/config \
-v ${mountpoint}:/myfiles \
--mount type=tmpfs,destination=/tmp \
--restart=always \
--name="filebrowser${suffix}" \
80x86/filebrowser:amd64
ExecStop=/usr/bin/docker stop filebrowser${suffix}

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload >> "$OutputLOG" 2>&1
}


function write_filebrowser_nginx_reverse_proxy () {
    # Nginx Reverse
    # Currently this is only for the first non-root user
    if [[ -d /etc/nginx/apps ]]; then
        cat << 'EOF' > /etc/nginx/apps/filebrowser.conf
location /fb {
  return 301 /fb/;
}

location /filebrowser {
  return 301 /filebrowser/;
}

location /fb/ {
  rewrite ^/fb/(.*) /$1 break;
  proxy_pass http://fb;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_set_header Host $host;
}

location /filebrowser/ {
  rewrite ^/filebrowser/(.*) /$1 break;
  proxy_pass http://filebrowser;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_set_header Host $host;
}
EOF
        cat << EOF > /etc/nginx/conf.d/filebrowser.conf
upstream filebrowser {
    server 127.0.0.1:${wPort};
}

upstream fb {
    server 127.0.0.1:${wPort2};
}
EOF
        nginx -s reload      >> "$OutputLOG" 2>&1
    fi
}


function filebrowser_root () {
    if [[ ! -f /root/.config/filebrowser-ee/database.db ]]; then
        create_filebrowser_conf      root
        create_filebrowser_systemd   root
      # systemctl enable filebrowser-root --now >> "$OutputLOG" 2>&1
    fi
}


function install_filebrowser_ee () {
    get_filebrowser_origin
    get_filebrowser_ee

    filebrowser_root
    create_filebrowser_conf       $iUser
    create_filebrowser_systemd    $iUser
    write_filebrowser_nginx_reverse_proxy
    systemctl enable filebrowser@${iUser} >> "$OutputLOG" 2>&1
    systemctl start  filebrowser@${iUser} >> "$OutputLOG" 2>&1

    check_if_succeed 20 "$AppTest"
    # Debug
    docker ps             >> "$OutputLOG" 2>&1
    echo "iUser=$iUser"   >> "$OutputLOG" 2>&1
    echo "waits=$waits"   >> "$OutputLOG" 2>&1

    generate_status_lock
}

################################################################################################

install_base docker
which docker > /dev/null || echo_error_exit "No Docker found"

if [[ -d $iHome/.config/filebrowser-ee ]] && [[ $force != 1 ]] ;then
    echo -e "Configuration for $iUser already exists, skip configuration ..."
else
    echo_task "Installing $AppName ..."
    install_filebrowser_ee & spinner $!
    check_status $AppNameLower
fi
